#-*- coding:UTF-8 -*-
__author__ = 'Frank Yang <frankyang418@gmail.com>'
__date__ = "2013-5-16 9:16"
__doc__ = u"程序入口"

import tornado
import tornado.web
from tornado.options import options, define
from etc import appconf, tornadoconf
from lib.helper import setting_from_objects

define('cmd', default='run', metavar='run|test|initdb')
define('port', default='3000', type=int, help=u"端口")
define('host', default='127.0.0.1', help=u"监听地址")


class Application(tornado.web.Application):
    def __init__(self):
        from etc.routes import urls
        handlers = urls
        settings = setting_from_objects(tornadoconf, appconf)
        tornado.web.Application.__init__(self, handlers, **settings)
        if settings['use_redis']:
            import redis

            pool = redis.ConnectionPool(
                host=settings['redis_host'],
                port=settings['redis_port'],
                db=settings['redis_db']
            )
            self.redis = redis.StrictRedis(connection_pool=pool)


if __name__ == '__main__':
    options.parse_command_line()
    if options.cmd == 'run':
        import tornado.httpserver
        import tornado.ioloop

        http_server = tornado.httpserver.HTTPServer(Application(), xheaders=True)
        http_server.listen(options.port, options.host)
        print "server is running at:http:%s:%d" % (options.host, options.port)
        tornado.ioloop.IOLoop.instance().start()
    elif options.cmd == 'test':
        pass
    elif options.cmd == 'initdb':
        pass
    else:
        options.print_help()